import os

# from Server.Utils import
import stat


class File():
    def __init__(self, path: str, name: str):
        self.path: str = path
        self.name: str = name
        self.relpath = os.path.join(path, name)
        self.check_exist()
        self.abspath = os.path.abspath(self.relpath)
        self.st = os.stat(self.abspath)
        self.stat = {}
        self.get_meta()

    def check_exist(self):
        if not os.path.isfile(self.relpath):
            raise Exception(f"Error, {self.relpath} is not a file")

    def get_meta(self):
        # st = os.stat(self.abspath)
        self.stat['name'] = self.name
        self.stat['mtime'] = self.st.st_mtime
        self.stat['type'] = 'file'
        self.stat['size'] = self.get_size()

    def get_size(self):
        st = os.stat(self.abspath)
        return st.st_size


class Folder(File):
    # def __init__(self, path: str, name: str):
    #     super(Folder).__init__(self,path, name)

    def check_exist(self):
        if not os.path.isdir(self.relpath):
            raise Exception(f"Error, {self.relpath} is not a folder")

    def get_meta(self):
        super().get_meta()
        self.stat['type'] = 'dir'
        # self.stat['name'] = self.name
        # self.stat['size'] = 4096
        # self.stat['mtime'] = self.st.st_mtime

    def get_size(self,type:int=0):
        if type==0:
            return 4096
        elif type==1:
            folder_size = 0
            for filename in self.sub_files():
                file = File(self.abspath, filename)
                folder_size += file.get_size()
                del file
            return folder_size
        elif type ==2:
            raise Exception("没有写完成计算文件夹大小的函数")

    def get_asize(self):
        raise Exception("求文件夹的绝对大小这部分程序我还没写呢")

    def sub_files(self):
        return [filename for filename in os.listdir(self.abspath) if os.path.isfile(filename)]

    def sub_folders(self):
        return [dirname for dirname in os.listdir(self.abspath) if os.path.isdir(dirname)]

    def sub_all(self):
        return [filename for filename in os.listdir(self.abspath)]


def fetch_file(path):
    bpath,name = os.path.split(path)
    if os.path.isfile(path):
        return File(bpath,name)
    elif os.path.isdir(path):
        return Folder(bpath,name)
    else:
        raise Exception(f"Error, the path {path} seems to be empty.")